

#include "iot.h"

void gettime(char *buf) 
{
	
	time_t tm;
	struct tm *pt;
	tm = time(NULL);
	pt = localtime(&tm);
	snprintf(buf, 100, "%4d-%02d-%02d %02d:%02d:%02d",
		pt->tm_year+1900, pt->tm_mon+1, pt->tm_mday,
		pt->tm_hour, pt->tm_min, pt->tm_sec);
}



/*
	函数名: 初始化打开数据库建表
	参数:
		ppdb 获取数据库句柄对象 输出参数
	


*/
void init_db(sqlite3 **ppdb)
{
	int ret;
	char *errmsg;
	//1.打开或创建数据库
	ret = sqlite3_open("myiot.db", ppdb);
	if (ret != SQLITE_OK) {
		fprintf(stderr, "sqlite3_open fail : %s\n", sqlite3_errmsg(*ppdb));
		exit(1);
	}
	//2.建表
	char sql[BUFSIZ] = "create table if not exists users(uname  varchar(20) primary key, pass  varchar(20), workid int, regdatatime char[100]);";

	ret = sqlite3_exec(*ppdb, sql, NULL, NULL, &errmsg);
	if (ret != SQLITE_OK) {
		fprintf(stderr, "sqlite3_exec fail : %s\n", errmsg);
		exit(1);
	}

}

/*
	函数名: do_regiset
	功能:注册用户名密码的注册函数
	参数:
		pdb 获取数据库句柄对象 输出参数
		username 注册用户名
		password 注册密码
	返回值:
		true --注册成功
		false -- 注册失败


*/

bool do_regiset(sqlite3 *pdb, char username[30], char password[30], int workid)
{
	int ret;
	char sql[BUFSIZ] = {0};
	
	
	char regdatatime[100];
	char *errmsg;

	gettime(regdatatime);
	snprintf(sql, BUFSIZ, 
		"insert into users values('%s', '%s', %d, '%s');", 
		username, password, workid, regdatatime);
	printf("%s\n", sql);
	ret = sqlite3_exec(pdb, sql, NULL, NULL, &errmsg);
	if (ret != SQLITE_OK) {
		fprintf(stderr, "sqlite3_exec fail : %s\n", errmsg);
		return false;
	}
	return true;

}


bool do_login(sqlite3 *pdb, char username[30], char password[30])
{
	
	int ret;	
	//4.查询用户表
	char **result;
	int rows, cols;
	char sql[BUFSIZ] = {0};
	char *errmsg;
	snprintf(sql, BUFSIZ, "select * from users where uname='%s' and pass='%s';", 
			username, password);


	ret = sqlite3_get_table(pdb, sql, &result, &rows, &cols, &errmsg);
	if (ret != SQLITE_OK) {
		fprintf(stderr, "sqlite3_get_table fail : %s\n", errmsg);
		exit(1);
	}

	printf("rows=%d\n", rows);
	printf("cols=%d\n", cols);	
	sqlite3_free_table(result);
	if (rows==0 && cols==0) {
		printf("login fail\n");
		return false;
	} else {
		printf("login success\n");
		return true;
	}


}
















